package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cloudfun.campusshare.common.constant.IdentityType;
import com.cloudfun.campusshare.common.constant.miniprogram.WeChatContractChangeType;
import com.cloudfun.campusshare.common.model.dto.WeChatContractSignNotifyDTO;
import com.cloudfun.campusshare.common.model.dto.WeChatNotifyRespDTO;
import com.cloudfun.campusshare.entity.UserAuthEntity;
import com.cloudfun.campusshare.entity.WeChatContractEntity;
import com.cloudfun.campusshare.repo.WeChatContractRepo;
import com.cloudfun.campusshare.service.UserAuthService;
import com.cloudfun.campusshare.service.WeChatContractService;
import com.cloudfun.campusshare.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * Created by Huqin on 2020/4/20
 */
@Slf4j
@Service
public class WeChatContractServiceImpl implements WeChatContractService {

    @Autowired
    private WeChatContractRepo weChatContractRepo;

    @Autowired
    private UserAuthService userAuthService;

    @Override
    @Transactional
    public WeChatNotifyRespDTO notify(WeChatContractSignNotifyDTO notifyDTO) {
        if (notifyDTO.getChangeType().equals(WeChatContractChangeType.DELETE)) {
            this.delete(notifyDTO.getOpenId());
            return WeChatNotifyRespDTO.success();
        }
        UserAuthEntity userAuthEntity = userAuthService.getByIdentityTypeAndIdentifier(IdentityType.WE_CHAT, notifyDTO.getOpenId());
        if (null == userAuthEntity) {
            return WeChatNotifyRespDTO.fail("根据openId找不到用户");
        }
        WeChatContractEntity weChatContractEntity = weChatContractRepo.findByCustomerId(userAuthEntity.getUserId());
        if (null == weChatContractEntity) {
            weChatContractEntity = new WeChatContractEntity();
        }
        BeanUtil.copyProperties(notifyDTO, weChatContractEntity, "operateTime");
        weChatContractEntity.setOperateTime(LocalDateTime.parse(notifyDTO.getOperateTime(), DateUtil.DATE_TIME_FORMATTER));
        // 设置userId
        weChatContractEntity.setCustomerId(userAuthEntity.getUserId());
        weChatContractRepo.save(weChatContractEntity);
        return WeChatNotifyRespDTO.success();
    }

    @Override
    public WeChatContractEntity getByCustomerId(String customerId) {
        if (StringUtils.isBlank(customerId)) {
            return null;
        }
        return weChatContractRepo.findByCustomerId(customerId);
    }

    @Override
    public void delete(String userId) {
        WeChatContractEntity WeChatContractEntity = weChatContractRepo.findByCustomerId(userId);
        weChatContractRepo.delete(WeChatContractEntity);
    }
}
